package com.tr.rentcar.model.dao;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import com.tr.rentcar.model.GlobalParamHandler;
import com.tr.rentcar.model.bean.UserDiscount;
import com.tr.rentcar.model.jdbc.MySqlDb;
import com.tr.rentcar.model.jdbc.ResultHandler;
/**
 * 优惠卷
 * @author lenovo
 *
 */

public class UserDiscountDao implements ResultHandler<UserDiscount>{
	private MySqlDb db= MySqlDb.getInstance();
	/**
	 * 根据用户id
	 * 查询是否含有此优惠券
	 * @return 
	 */
	public  UserDiscount didAndUid(int did,Integer uid) throws SQLException {
		String sql = "select * from  user_discoun_he WHERE did=? AND uid=?";
		return db.queryUninResult(sql, new GlobalParamHandler(did,uid), this);
	}
	/**
	 * 查询所有有
	 */
	public List<UserDiscount> findAll() throws SQLException {
		String sql = "select * from  user_discoun_he";
		return db.executeQuery(sql,this);
	}
	/**
	 * 根据用户id查寻用户优惠券
	 */
	public List<UserDiscount> findById(int uid) throws SQLException {
		String sql = "select * from user_discoun_he where uid = ? order by ud_date desc";
		return db.executeQuery(sql, new GlobalParamHandler(uid), this);
	}
	/**
	 * 为用户存入此优惠券
	 * 
	 */
	public boolean saveDiscount(Integer uid,Integer did) throws SQLException {
		String sql = "INSERT INTO user_discount SET uid=?, did=?";
		return db.executeUpdate(sql, new GlobalParamHandler(uid,did)) > 0;
	}
	
	/**
	 * 删除指定用户的指定优惠券
	 * @param uid
	 * @param did
	 * @return
	 * @throws SQLException
	 */
	public boolean deleteDiscount(int uid,int did) throws SQLException{
		String sql="delete from user_discount where uid=? and did=?";
		return db.executeUpdate(sql, new GlobalParamHandler(uid,did))>0;
		}
	
	@Override
	public UserDiscount doHander(Map<String, Object> row) {
		UserDiscount ud=new UserDiscount();
		ud.setdName(row.get("dname")+"");
		Integer in=Integer.parseInt(row.get("dtime")+"") ;
		ud.setdTime(in);
		ud.setUdId(Integer.parseInt(row.get("ud_id")+""));
		ud.setuId(Integer.parseInt(row.get("uid")+""));
		ud.setDdiscount((Double)row.get("ddiscount"));
		Date da=(Date)row.get("ud_date");
		ud.setUdDate(da);
		Integer did=Integer.parseInt(row.get("did")+"") ;
		ud.setDid(did);
		//计算过期时间
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(da); 
		calendar.add(calendar.DATE,in);
		Date da2=new Date();
		da2 = calendar.getTime(); 
		ud.setUgDate(da2);
		//计算剩余时间
		Date ss=new Date();
		int temp;
		if (da2.getTime()>ss.getTime()) {
			temp = (int)((da2.getTime() - ss.getTime())/(24 * 60 * 60 * 1000));
		}else {
			temp=-1;
		}
		if (temp>0) {
			ud.setUdsTime(temp+"天");
		}else if (temp==0) {
			ud.setUdsTime("不足一天");
		}else {
			ud.setUdsTime("已过期");
		}
		
		return ud;
	}
}
